package com.cuit.controller;

import com.cuit.doamin.Recruitment;
import com.cuit.service.RecruitmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/recruit")
public class RecruitmentController {

    @Autowired
    private RecruitmentService recruitmentService;

    @RequestMapping("/find")
    public ModelAndView find() {
        ModelAndView mv = new ModelAndView();

        List<Recruitment> list = recruitmentService.find();
        mv.addObject("list", list);
        mv.setViewName("admin/find_recruitment");
        return mv;
    }

    @RequestMapping("/findRecruit")
    public ModelAndView findRecruit() {
        ModelAndView mv = new ModelAndView();

        List<Recruitment> list = recruitmentService.find();
        mv.addObject("list", list);
        mv.setViewName("user/find_recruit");
        return mv;
    }

    @RequestMapping("/delete")
    public ModelAndView delete(Integer id) {
        ModelAndView mv = new ModelAndView();

        boolean b = recruitmentService.delete(id);
        if (b) {
            mv.setViewName("pages/success");
        } else {
            mv.setViewName("pages/error");
        }
        return mv;
    }

    @RequestMapping("/fpost")
    public ModelAndView findPost() {
        ModelAndView mv = new ModelAndView();

        List<Recruitment> post = recruitmentService.findPost();
        mv.addObject("post", post);

        mv.setViewName("admin/find_post");
        return mv;
    }

    /**
     * 上传简历
     *
     * @param upload
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public String upload(String type, MultipartFile upload, HttpServletRequest request) throws IOException {

        String sqlpath = request.getSession().getServletContext().getRealPath("/images/recruit/");
        System.out.println(sqlpath);

        File file = new File(sqlpath);
        if (!file.exists()) {
            file.mkdirs();
        }

        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = uuid + upload.getOriginalFilename();
        upload.transferTo(new File(sqlpath, filename));

        Recruitment recruitment = new Recruitment();
        recruitment.setR_type(type);
        recruitment.setR_details(filename);

        boolean b = recruitmentService.add(recruitment);
        if (b) {
            return "pages/success";
        } else {
            return "pages/error";
        }
    }
}
